package com.xxxx.paipaicars.utils;


import org.apache.commons.collections4.MapUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * ThreadLocal工具类
 */
@SuppressWarnings("all")
public class ThreadLocalUtil {

    /**
     * 线程存储池子
     */
//    private static final ThreadLocal<Map<String, Object>> threadLocal = ThreadLocal.withInitial(() -> new HashMap<>(10));// 下面代码等价
    private static final ThreadLocal<Map<String, Object>> threadLocal = new InheritableThreadLocal<>();

    /**
     * 获取当前线程ThreadLocal
     *
     * @return Map
     */
    public static Map<String, Object> getThreadLocal() {
        return threadLocal.get();
    }

    /**
     * 获取当前线程存储池子中指定信息
     *
     * @param key 指定key
     * @param <T> 泛型
     * @return 指定值
     */
    public static <T> T get(String key) {
        Map<String, Object> map = threadLocal.get();
        return get(key, null);
    }

    /**
     * 获取当前线程存储池子中指定信息
     *
     * @param key          指定key
     * @param defaultValue 默认值
     * @param <T>          泛型
     * @return 指定值
     */
    public static <T> T get(String key, T defaultValue) {
        Map<String, Object> map = threadLocal.get();
        return (T) Optional.ofNullable(map.get(key)).orElse(defaultValue);
    }

    /**
     * 设置值到当前线程存储池子中
     *
     * @param key   键
     * @param value 值
     */
    public static void set(String key, Object value) {
        Map<String, Object> map = threadLocal.get();
        map.put(key, value);
    }

    /**
     * 设置值到当前线程存储池子中
     *
     * @param keyValueMap 值map
     */
    public static void set(Map<String, Object> keyValueMap) {
        Map<String, Object> map = threadLocal.get();
        if (MapUtils.isEmpty(map)) {
            map = new HashMap<>();
            map.putAll(keyValueMap);
            // 初始化map的同时放入到线程中
            threadLocal.set(map);
        } else {
            map.putAll(keyValueMap);
        }
    }

    /**
     * 清除threadlocal信息
     */
    public static void remove() {
        threadLocal.remove();
    }

    /**
     * 清除threadlocal指定key信息
     */
    public static <T> T remove(String key) {
        Map<String, Object> map = threadLocal.get();
        return (T) map.remove(key);
    }


}

